import { ListState } from "../../hooks/useFetchList";

export interface CarState {
  carList: CarListState[];
}

export interface CarListState extends ListState {
  // 购买数量
  count: number;
  // 选中状态
  state: boolean;
}

const initState: CarState = {
  carList: JSON.parse(localStorage.getItem('carList') || '[]'), 
};

export const carReducer = (state = initState, action: any) => {
  switch (action.type) {
    // 加入购物车
    case 'addCarList': {
      // action.payload  => CarListState
      // state.carList   => CarListState[]

      // 1. 查找数据 根据ID
      const item = state.carList.find(v => v.id === action.payload.id)
      // 2. 找到了  数量++
      if(item) { 
        item.count++ 
      }
      // 3. 没找到  推入新商品
      else {
        state.carList.push({ ...action.payload })
      }
      
      return {
        ...state,
        carList: [...state.carList]
      }
    }
    // 减少购物车
    case 'jianlist': {
       // 1. 查找数据 根据ID
       const item = state.carList.find(v => v.id === action.payload.id)
       // 2. 找到了  数量--
       if(item) { 
         item.count--
       }
       console.log('jianlist', state.carList)
       return {
         ...state,
         carList: [...state.carList]
       }
    }
    // 删除购物车
    case 'delCarList': {
      const result = state.carList.filter(v => v.id !== action.payload.id);

      return {
        ...state,
        carList: result
      }
    }
    // 单选状态改变
    case 'checkedCarList': {
      const item = state.carList.find(v => v.id === action.payload.id);
      if(item) {
        item.state = !item.state
      }
      return {
        ...state,
        carList: [...state.carList]
      }
    }
    // 全选状态改变
    case 'allChecked': {
      state.carList.forEach(v => v.state = action.payload)
      return {
        ...state,
        carList: [...state.carList]
      }
    }
    default:
      return state;
  }
};
